<?php
namespace Admin\Controller;

/**
 * 财务管理
 *
 */

use Think\Controller;
use Common\Controller\BaseController;
use Common\ORG\Page;

class MoneyController extends BaseController {

	public function index()
	{
		$wheres = array();
		$wheres['_string'] = '1=1';
		$psize = I('get.psize', $this->m_psize,'intval');
		$audit = I('get.audit', -1, 'intval');
		$sales = I('get.sales', '', 'trim');
		$pay_name = I('get.pay_name', '', 'trim');
		$customer_name = I('get.customer_name', '', 'trim');
		$pay_way = I('get.pay_way', '-1', 'trim');
		$stime = I('get.stime', '', 'trim');
		$etime = I('get.etime', '', 'trim');
		$status = I('get.status', 1, 'intval');

		$psize = !$psize||$psize>50 ? $this->m_psize : $psize;
		$Mdo = D('Admin/Pays');

		if (-1 != $audit)
			$wheres['p.audit_res'] = array('eq', $audit );
		if ('-1' != $pay_way && $pay_way)
			$wheres['p.pay_way'] = array('eq', $pay_way );

		if ($customer_name) {
			if (preg_match('#^\d{4,13}$#', $customer_name )) {
                $MPhoneBook = D('Admin/CustomerPhonebook');
                $wherep = array();
                $wherep['book_phone'] = array('like','%'.$customer_name.'%');
                $_arr_phones = $MPhoneBook->field("customer_id")->where( $wherep )->select();
                $arr_phones = array();
                foreach ($_arr_phones as $kp => $vp) {
                    $arr_phones[] = $vp['customer_id'];
                }
                if( !$arr_phones )
                    $arr_phones[] = 0;
                $wheres['c.customer_id'] = array('in', $arr_phones );
            }
            else if (substr($customer_name, 0,2) == 'AA') {
                $wheres['c.customer_code'] = array('like', $customer_name.'%');
            }
            else {
            	$wheres['c.nickname'] = array('like', '%'.$customer_name.'%');
            }
		}
		if ($pay_name) {
        	$wheres['p.pay_name'] = array('like', '%'.$pay_name.'%');
		}
		if ($sales) {
			$MUser = D('Admin/User');
            $whereu = array();
            $whereu['nickname'] = array('like', '%'.$sales.'%');
            $_arr_users = $MUser->field('user_id')->where( $whereu )->select();
            $arr_users = array();
            foreach( $_arr_users as $vau ){
                $arr_users[] = $vau['user_id'];
            }
            if( !$arr_users) $arr_users[] = 0;
            $wheres['p.sales_person'] = array('in', $arr_users );
		}

		if ($stime || $etime ) {
			if ($stime&&$etime){
				$tm_s = strtotime($stime);
				$tm_s = strtotime('-1days', $tm_s );
				$tm_e = strtotime($etime);
				$stime = date('Y-m-d 23:59:59', $tm_s );
				$etime = date('Y-m-d 23:59:59', $tm_e );
				$wheres['p.pay_time'] = array('between', array($stime, $etime));
			}
			else if ($stime) {
				$tm = strtotime($stime);
				$tm = strtotime('-1days', $tm );
				$st = date('Y-m-d 23:59:59', $tm );
				$wheres['p.pay_time'] = array('gt', $st);
			}
			else if ($etime) {
				$tm = strtotime($etime);
				$st = date('Y-m-d 23:59:59', $tm );
				$wheres['p.pay_time'] = array('lt', $st);
			}
		}
		if ( $status )
			$wheres['record_status'] = array('eq', $status );

		$cnt = $Mdo->alias("p")
				    ->join('LEFT JOIN customer  c ON c.customer_id = p.customer_id')
				    ->join('LEFT JOIN product ON product.product_id = p.customer_product')
				    ->join('LEFT JOIN user s ON s.user_id = p.sales_person')
					->where($wheres)
					->count();

		$Page = new \Common\ORG\Page( $cnt, $psize );
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$list = $Mdo->alias("p")
					->field('p.*,c.nickname,c.customer_id,product.name,s.nickname as username,cu.nickname as createname')
					->join('LEFT JOIN customer c ON c.customer_id = p.customer_id')
					->join('LEFT JOIN product ON product.product_id = p.customer_product')
					->join('LEFT JOIN user s ON s.user_id = p.sales_person ')
					->join("LEFT JOIN user cu ON cu.user_id=p.creator")
					->order('p.create_time desc')
					->where( $wheres )
					->limit($Page->firstRow.','.$Page->listRows )
					->select();

		$res['rcode'] = 1;
		$res['data'] = $list;
		$res['pall'] =  $Page->getTotalPages();
		$res['p'] = $Page->nowPage;
		$res['psize'] = $psize;

		e_json($res);
	}

	// 获取付款方式信息
	public function paytypes()
	{
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$MParam = D('Admin/SysParamDetail');
		$wheres = array();
		$wheres['sp.key_name'] = array('eq', 'PAY_WAY');
		$_payways = $MParam->alias("spd")
						   ->field("spd.detail_name as v")
						   ->join("LEFT JOIN sys_param sp on sp.sys_param_id=spd.sys_param_id")
						   ->where( $wheres )
						   ->order("spd.detail_order asc")
						   ->select();
		$payways = array();
		$item = array();
		foreach( $_payways as $vp ){
			$item['k'] = $vp['v'];
			$item['v'] = $vp['v'];
			$payways[] = $item;
			$index++;
		}
		$res['data'] = $payways;
		e_json( $res );
	}

    /*
    *获取提交人信息
    */
	public function getCreator(){
		$pay= D('PayRecord');
		$res = $pay->gotapp();
		e_json($res);
	}
    /*
    *审核
    */
	public function auditVerify(){
		$payrecord = I('get.payrecord_id');
		if($_GET['identify'])
		{
			$map['audit_res'] = 2;
		}
		else
		{
			$map['audit_res'] = 1;
		}
		$where['payrecord_id'] = $payrecord;
		$verify = M('pay_record')->where($where)->save($map);
		if($verify){
			$res['rcode'] = 1;
			if($_GET['identify'])
			{
				$res['msg'] = '请重新评论审核信息';
			}
			else
			{
				$res['msg'] = '审核成功';
			}
			
		}else{
			$res['msg'] = '审核失败、请核对信息';
		}
		e_json($res);
	}

	//退款审核
	public function Verfed($format='Y-m-d H:i:s'){
		$res = array('rcode'=>-1,'msg'=>'服务器忙，请稍候再试','data'=>null);
		$info = I('get.info','','trim');
		$identify = I('get.identify',false,'trim');
		$pay_way = I('get.paytype','','trim');
		$payrecord_id = I('get.payrecord_id',false,'intval');
		if ($identify == 1) {
			$res_rbk  = D('PayRecord')->ver_fed(array('audit_msg'=>$info,'pay_way'=>$pay_way,'payrecord_id'=>$payrecord_id));
			if ($res_rbk['rcode']) {
				$res['rcode']=1;
				$res['msg'] = 'ok';
				$res['data'] =  D('PayRecord')->where(array('payrecord_id'=>$payrecord_id))->find();
			}
		}else{
			$Reuser = M('user')->where(array('user_id'=>D('PayRecord')->Guid()))->find();
			$payres = D('PayRecord')->where(array('payrecord_id'=>$payrecord_id))->find();
			if ($payres) {
				$arr = array();
				$arr['auditor']=D('PayRecord')->Guid();
				$arr['audit_sector']=$Reuser['sector_id'];
				$arr['audit_role'] = $Reuser['role_id'];
				$arr['payrecord_id'] = $payrecord_id;
				$arr['audit_msg'] = $info;
				$arr['audit_time']=date($format);
				// $arr['pay_way'] = $pay_way;
				$arr['audit_res'] = 2;
				$paysave = D('PayRecord')->save($arr);
				if ($paysave) {
					$res['rcode']=1;
					$res['msg'] = 'ok';
					$res['data'] = D('PayRecord')->where(array('payrecord_id'=>$payrecord_id))->find();
					$res['result'] = 'aa';
				}else{
					$res['msg'] = '请重新评论审核信息';
					$res['result'] = 'bb';
					$res['tt'] = $paysave;
				}
			}else{
				$res['msg']='查账信息不存在';
			}
		}

		e_json($res);
	}


	// 获得记录
	public function getrecord(){
		$res = array('rcode'=>-1,'msg'=>'服务器忙，请稍候再试','data'=>null);
		$customer_id = I('get.customer_id',false,'trim');
		$contract_id = I('get.contract',false,'trim');
		$record = D('PayRecord')->field('customer.nickname,pay_record.*')
								->join('customer ON customer.customer_id = pay_record.customer_id')
								->where(array('pay_record.customer_id'=>$customer_id,'pay_record.audit_res'=>1))
								->order('pay_time desc')
								->limit(5)
								->select();
		if ($record) {
			$res['rcode'] = 1;
			$res['data'] = $record;
			$res['msg'] = 'ok';
		}
		e_json($res);
	}

    /*
    *查账导出
    */
    public function excel_runexport(){
			// reference
			import("Common.ORG.Excel");
			$SExcel = new \Common\ORG\Excel();
			$SSheet = new \Common\ORG\Sheet("撞单数据");
			// set table header content
			$column = array('月份','新单周','到账日期','客户姓名','购买产品','开通日期','服务期限','打款人','缴费方式','到账金额','原单人员','手机号','性别','续费人员','资源渠道','合同报价','开通短信','QQ','微信号','备注','销售平台','平台数据','是否签合','资金量','续费类型');
			$SSheet->setColumn( $column );
			$createtime = I('get.createtime','','trim');
		 	$endtime = I('get.endtime','','trim');
		 	$checkperson =I('get.checkperson','','trim');
			$arr = array();
			$wheres = array();
			$vv = array();
			$arr['pay_record.create_time']=array('between',array($createtime,$endtime));
			$arr['pay_record.is_export'] = array('neq',1);
			$arr['pay_record.creator'] = $checkperson;



			$payrecord = D('PayRecord');

			$res = $payrecord->field('pay_record.customer_name,pay_record.customer_mount,pay_record.customer_note,pay_record.customer_qq,pay_record.customer_phone,pay_record.pay_name,pay_record.pay_mount,pay_record.customer_sex,pay_record.xufei_type,pay_record.customer_weixin_id,pay_record.pay_type,product.name,product.create_time,product_price.service_time,source.name,user.nickname,pay_record.payrecord_id')
							// ->table('payrecord as a')
			                // ->join('user  ON payrecord.creator = user.user_id')
			                ->join('LEFT JOIN contract  ON pay_record.contract_id = contract.contract_id')
			                ->join('LEFT JOIN source ON pay_record.customer_source = source.source_id')
			                ->join('LEFT JOIN product ON pay_record.customer_product = product.product_id')
			                ->join('LEFT JOIN product_price ON product.product_id = product_price.product_id')
			                ->join('LEFT JOIN customer_xufei ON pay_record.customer_id = customer_xufei.customer_id')
			                ->join('LEFT JOIN user ON customer_xufei.user_id = user.user_id')
			                ->where($arr)->select();
			    foreach ($res as $k1 => $v1) {
			    	if ($v1['xufei_type'] == 0) {
			    		$v1['xufei_type1'] = '补款';
			    	}elseif($v1['xufei_type'] == 1){
			    		$v1['xufei_type'] ='前续';
			    	}elseif($v1['xufei_type'] == 2){
			    		$v1['xufei_type'] = '后续';
			    	}
			    	if ($v1['pay_type'] == 0) {
			    		$v1['pay_type'] ='未知';
			    	}elseif ($v1['pay_type'] == 1) {
			    		$v1['pay_type'] ='新单';
			    	}elseif($v1['pay_type'] == 2){
			    		$v1['pay_type'] ='续费';
			    	}
			    	if ($v1['customer_sex'] == 1) {
			    		$v1['customer_sex'] = '男';
			    	}else{
			    		$v1['customer_sex'] = '女';
			    	}
			    	$res[$k1]=$v1;
			    }
			 // $aa = $payrecord->getLastSql();
			foreach ($res as $k => $v) {
				$vv['is_export'] = 1;
				$vv['payrecord_id'] = $v['payrecord_id'];
				$Ra = $payrecord ->save($vv);
			}

			if( $res ){
				foreach($res as $vd ){
					$row = array();
					$row[] = $vd['sector_name'];
					$row[] = $vd['pay_way'];
					$row[] = $vd['pay_mount'];
					$row[] = $vd['customer_name'];
					$row[] = $vd['name'];
					$row[] = $vd['create_time'];
					$row[] = $vd['service_time'];
					$row[] = $vd['pay_name'];
					$row[] = $vd['pay_type'];
					$row[] = $vd['pay_mount'];
					$row[] = $vd['customer_phone'];
					$row[] = $vd['customer_sex'];
					$row[] = $vd['nickname'];
					$row[] = $vd['customer_qq'];
					$row[] = $vd['customer_weixin_id'];
					$row[] = $vd['customer_note'];
					$row[] = $vd['claim_user_subcompany'];
					$row[] = $vd['customer_mount'];
					$row[] = $vd['xufei_type'];
					$SSheet->addRow( $row );
				}
			}

			$exportData = $SExcel->add_sheet( $SSheet)->export_sheet("查账数据导出");
			if( $exportData['rcode'] ){
				$exportData['name'] = basename( $exportData['data']['view_path'] );
				$exportData['excel'] = file_get_contents( $exportData['data']['real_path'] );
				echo $exportData['excel'];
				exit();
			}
      }

    //业绩统计
    public function statistics(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> '','verify'=>0);
		$psize = I('get.psize', $this->m_psize,'intval');
		$p = I('get.p','','intval');
		$S_time = I('get.start','','trim');
		$E_time = I('get.end','','trim');
		$S_ver = I('get.S_ver',false,'trim');
		if ($S_ver == 1) {
			$statistic = D('PayRecord')->getrole();
			$role_back = D('PayRecord')->Choose_role(array('trans'=>$statistic,'start_time'=>$S_time,'end_time'=>$E_time));

			$cnt = sizeof($role_back);
			$Page = new \Common\ORG\Page( $cnt, $psize );
			$dlist = array();
			for($i=($p-1)*$psize;$i<$p*$psize;$i++){
				if($role_back[$i]){
					$dlist[$i] = $role_back[$i];
				}
			}
			if($dlist){
				$res['rcode'] = 1;
				$res['data'] = $dlist;
				$res['pall'] = $Page->getTotalPages();
				$res['p'] = $Page->nowPage;
				$res['psize'] = $psize;
				$res['verify'] = 1;
			}else{
				$res['msg'] = '员工业绩统计搜索失败';
			}

		}else{
			$statistic_sector = D('PayRecord')->getchild();
			$sector_back = D('PayRecord')->choose_sector(array('trans'=>$statistic_sector,'start_time'=>$S_time,'end_time'=>$E_time));

			$cnt = sizeof($sector_back);
			$Page = new \Common\ORG\Page( $cnt, $psize );
			$dlist = array();
			for($i=($p-1)*$psize;$i<$p*$psize;$i++){
				if($sector_back[$i]){
					$dlist[$i] = $sector_back[$i];
				}
			}
			if($dlist){
				$res['rcode'] = 1;
				$res['data'] = $dlist;
				$res['pall'] = $Page->getTotalPages();
				$res['p'] = $Page->nowPage;
				$res['psize'] = $psize;
				$res['verify'] = 1;
			}else{
				$res['msg'] = '部门业绩统计搜索失败';
			}
		}
		e_json($res);
    }

    /*开发票时，根据客户id获取客户名*/
    public function getCusName(){
    	$res = array('rcode'=>0,'c'=>NULL, 'msg'=> 'OK');
		$customer_id = I('post.customer_id',false,'intval');
		$wheres = array();
		$wheres['customer_id'] = array('eq',$customer_id);
		$customerNameArr = M('Customer')->field("nickname")->where($wheres)->find();
		if($customerNameArr){
			$res['data'] = $customerNameArr;
			$res['rcode'] = 1;
		}else{
			$res['msg'] = '获取客户名失败！';
		}
		e_json($res);
    }

	/**
	* 退款记录,有的内容财务需要审核
	*/
	public function refund()
	{
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		if ( IS_GET ) {
			$Mdo = D('Admin/Refund');
			$wheres = array();

			$wheres['_string'] = '1=1';
			$wheres['r.is_delete'] = array('neq', 1);
			$status = I('get.status', -1, 'intval');
			$sales = I('get.sales', '', 'trim');
			$psize = I('get.psize', $this->m_psize, 'intval');
			$stime  = I('get.stime','' , 'trim');
			$etime  = I('get.etime','' , 'trim');
			$customer = I('get.customer', '', 'trim');

			$psize = !$psize||$psize>100 ? $this->m_psize: $psize;
			if ( -1 != $status ) {
				$wheres['r.status'] = array('eq', $status );
			}
			if ($sales) {
				$MUser = D('Admin/User');
				$whereu = array();
				$whereu['nickname'] = array('like', '%'.$sales.'%');
				$subsql = $MUser->field("user_id")->where( $whereu )->buildSql();
				$wheres['_string'] = ' r.sales_id in '.$subsql;
			}

			if ($customer) {
				if( preg_match('#^\d{4,13}$#', $customer )){
	                $MPhoneBook = D('Admin/CustomerPhonebook');
	                $wherep = array();
	                $wherep['book_phone'] = array('like','%'.$customer.'%');
	                $_arr_phones = $MPhoneBook->field("customer_id")->where( $wherep )->select();
	                $arr_phones = array();
	                foreach ($_arr_phones as $kp => $vp) {
	                    $arr_phones[] = $vp['customer_id'];
	                }
	                if( !$arr_phones )
	                    $arr_phones[] = 0;
	                $wherec = array();
	                $wherec['_logic'] = 'or';
	                $wherec['c.customer_id'] = array('in', $arr_phones);
	                $wherec['r.phone'] = array('like','%'.$customer.'%');
	                $wheres['_complex'] = $wherec;
	            }
	            else if (substr($customer, 0,2) == 'AA') {
	                $wheres['c.customer_code'] = array('like', $customer.'%');
	            }
	            else{
	                $wheres['c.nickname'] = array('like', '%'.$customer.'%');
	            }
			}

			if ($stime||$etime) {
				if ($stime&&$etime) {
					$tm_s = strtotime($stime);
					$tm_e = strtotime($etime);
					$stime = date('Y-m-d 0:0:0', $tm_s );
					$etime = date('Y-m-d 23:59:59', $tm_e );
					$wheres['r.create_time'] = array('between', array($stime, $etime));
				}
				else if ($stime) {
					$tm_s = strtotime($stime);
					$stime = date('Y-m-d 0:0:0', $tm_s );
					$wheres['r.create_time'] = array('gt', $stime);
				}
				else if ($etime) {
					$tm_s = strtotime($etime);
					$stime = date('Y-m-d 23:59:59', $tm_s );
					$wheres['r.create_time'] = array('lt', $stime);
				}
			}
			$cnt = $Mdo->alias("r")
					   ->join("LEFT JOIN customer c on c.customer_id=r.customer_id")
					   ->where( $wheres )
					   ->count();

		 	$Page = new Page( $cnt, $psize );
			$list = $Mdo->alias("r")
						->field("r.*,c.nickname as customer_name,su.nickname as sales_name,ra.detail_value as reason,mu.nickname as manager_name,s.sector_name as team")
						->join("LEFT JOIN customer c on c.customer_id=r.customer_id")
						->join("LEFT JOIN user su on su.user_id=r.sales_id")
						->join("LEFT JOIN user mu on mu.user_id=r.sales_manager")
						->join("LEFT JOIN sector s on s.sector_id=r.sales_subcompany")
						->join("LEFT JOIN sys_param_detail ra on ra.sys_param_detail_id=r.reason_id")
						->where( $wheres )
						->limit( $Page->firstRow.','.$Page->listRows )
						->order("r.create_time desc")
						->select();
			foreach ($list as &$vk) {
				$vk['phone'] = phone_mask($vk['phone']);
			}
			$res['rcode'] = 1;
            $res['data']  = $list;
            $res['page']    =  $Page->getTotalPages();
            $res['p']       = $Page->nowPage;
            $res['psize']   = $psize;
		}
		else {
			//
		}
		e_json($res);
	}

	private function _findRefund( $_id )
	{
		$res = false;
		$Mdo = D('Admin/Refund');

		$wheres = array();
		$wheres['r.refund_id'] = array('eq', $_id );

		$ret = $Mdo->alias("r")
						->field("r.*,c.nickname as customer_name,su.nickname as sales_name,ra.detail_value as reason,mu.nickname as manager_name,s.sector_name as team")
						->join("LEFT JOIN customer c on c.customer_id=r.customer_id")
						->join("LEFT JOIN user su on su.user_id=r.sales_id")
						->join("LEFT JOIN user mu on mu.user_id=r.sales_manager")
						->join("LEFT JOIN sector s on s.sector_id=r.sales_subcompany")
						->join("LEFT JOIN sys_param_detail ra on ra.sys_param_detail_id=r.reason_id")
						->where( $wheres )
						->find();

		if ($ret) {
			$res['refund'] = $ret;
			//详细退款流水信息
			$MPay = D('Admin/Pays');
			$wherep = array();
			$wherep['p.record_status'] = array('eq', 1);
			$wherep['rp.refund_id '] = array('eq', $_id);

			$res['pays'] = $MPay->alias("p")
								->field("p.contract_id as cid,p.pay_id,p.pay_time,p.pay_name,p.pay_mount,p.pay_way,p.audit_res,p.refund_mount as pmount,rp.refund_mount,
								s.sector_name as team,su.nickname as sales_name,mu.nickname as manager_name")
								->join("LEFT JOIN user su on su.user_id=p.sales_person")
								->join("LEFT JOIN user mu on mu.user_id=p.sales_manager")
								->join("LEFT JOIN sector s on s.sector_id=p.sales_sub_company")
								->join("LEFT JOIN refund_pays rp on rp.pay_id=p.pay_id")
								->where( $wherep )
								->order()
								->select();
			foreach ($res['pays'] as &$vp) {
				if(!$vp['pmount'])
					$vp['pmount'] = 0.00;
			}
			//退款协议邮寄信息
			$res['delivery'] = array();
		}
		return $res;
	}

	/**
	* 退款确认
	*/
	public function refundConfirm()
	{
		##TODO:将邮寄状态换成类名日常量
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$Mdo = D('Admin/Refund');
		$id = I('get.id', 0, 'intval');
		//获取退款基本信息
		$data = $this->_findRefund( $id );

		if (IS_GET) {
			if ( $data && intval($data['refund']['status'] == 30 ) ) { // //待财务审核状态
				$data['refund']['pay_time'] = date('Y-m-d');
				$res['rcode'] = 1;
				$res['msg'] = 'ok';
				$res['data'] = $data;
			}
			else if ( $data && intval($data['status'] != 30 ) ) {
				$res['msg'] = "该退款信息不能确认打款!";
			}
			else
				$res['msg'] = "获取退款信息失败";
		}
		else { //POST
			if ($data&& intval( $data['refund']['status'])==30) {  //待财务审核状态
				$pay_name = I('post.pay_name', '', 'trim');
				$pay_way = I('post.pay_way', '', 'trim');
				$pay_time = I('post.pay_time', '', 'trim');
				$audit_msg = I('post.audit_msg', '', 'trim');
				$audit = I('post.audit', -1, 'intval');
				if (-1==$audit || !$audit_msg) {
					$res['msg'] = "提交参数错误";
				}
				else if ($audit && (!$pay_name||!$pay_time||!$pay_way)) {
					$res['msg'] = "提交参数错误";
				}
				else if ($audit) {
					//退款金额流水检查
					$pay_check_ok = ture;
					foreach ($data['pays'] as $vp) {
						$p_mount =  doubleval($vp['pay_mount']);
						$p_refunded = doubleval($vp['pmount']);
						$p_refund = doubleval($vp['refund_mount']);
						if ($p_mount <($p_refunded + $p_refund) ){
							$pay_check_ok = false;
							break;
						}
					}
					if (!$pay_check_ok) {
						$res['msg'] = "退款金额超过付款总金额";
					}
					else {
						$MPay = D('Admin/Pays');
						$MContract = D('Admin/Contract');
						$dcon = array();
						$dcon['is_refund'] = 1;
						$payUp = $wherep = $wherecon = $refundUp = array();
						$refundUp['finance_audit_msg'] = $audit_msg;
						$wherep['record_status'] = array('eq', 1);
						foreach ($data['pays'] as $vp) {
							$wherep['pay_id'] = array('eq', $vp['pay_id']);
							$mount = doubleval($vp['pmount']) +  doubleval($vp['refund_mount']);
							$payUp['refund_mount'] = $mount;
							$MPay->where( $wherep )->save( $payUp );

							//付款关联合同进行退款标识
							$wherecon['contract_id'] = array('eq', $vp['cid']);
							$MContract->where( $wherecon )->save( $dcon );
						}
						$refundUp['status'] = '40';
						$refundUp['pay_name'] = $pay_name;
						$refundUp['pay_way'] = $pay_way;
						$refundUp['pay_time'] = date('Y-m-d H:i:s', strtotime( $pay_time ));
						$wheres = array();
						$wheres['refund_id'] = array('eq', $id );
						$cnt = $Mdo->where( $wheres )->save( $refundUp );

						//更新合同信息
						if ($cnt) {
							$res['rcode'] = 1;
							$res['msg'] = 'OK';
						}
						else {
							$res['msg'] = "数据更新失败";
						}
					}
				}
				else if (!$audit) {
					$up = array();
					$wheres = array();
					$wheres['refund_id'] = array('eq', $id );
					$up['finance_audit_msg'] = $audit_msg;
					$up['status'] = 31;
					$cnt = $Mdo->where( $wheres )->save( $up );
					if ($cnt) {
						$res['rcode'] = 1;
						$res['msg'] = "数据更新成功";
						$res['data'] = $cnt;
					}
					else
						$res['msg'] = "数据更新失败";
				}
			}
			else
				$res['msg'] = "退款无法审核";
		}

		e_json($res);
	}

	/**
	*退款审核成功之后可以查看
	*/
	public function refundView()
	{
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$id = I('get.id', 0, 'intval');

		if (IS_GET) {

			$data = $this->_findRefund( $id );
			if ($data&& intval( $data['refund']['status'])==40) {
				$res['rcode'] = 1;
				$res['data'] = $data;
				$res['msg'] = 'OK';
			}
			else if ($data&& intval( $data['status']) != 40 ) {
				$res['msg'] = "退款未审核成功，不能查看";
			}
			else {
				$res['msg'] = "获取退款数据失败";
			}
		}

		e_json($res);
	}

	/**
	* 撞单记录查看
	*/
	public function conflict()
	{
		//
	}
}